package com.cloudbroker.bcs.platform.dav.middle.bizservice.impl;

import java.util.ArrayList;
import java.util.Date;
import java.util.Iterator;
import java.util.List;

import javax.annotation.Resource;

import net.sf.json.JSONArray;
import net.sf.json.JSONObject;

import org.apache.log4j.Logger;
import org.apache.velocity.runtime.parser.node.MathUtils;
import org.springframework.stereotype.Service;

import com.cloudbroker.bcs.common.entity.HSBCPSBackVO;
import com.cloudbroker.bcs.common.model.Pagination;
import com.cloudbroker.bcs.common.util.DateUtil;
import com.cloudbroker.bcs.common.util.StringUtil;
import com.cloudbroker.bcs.common.util.VOUtil;
import com.cloudbroker.bcs.platform.dav.bizapi.constants.HSBCPSErrorCodes.ClientErr;
import com.cloudbroker.bcs.platform.dav.bizapi.constants.HSBCPSErrorCodes.ExtendGroupErr;
import com.cloudbroker.bcs.platform.dav.bizapi.constants.HSBCPSErrorCodes.PlugsErr;
import com.cloudbroker.bcs.platform.dav.bizapi.constants.HSBCPSErrorCodes.WechatShareErr;
import com.cloudbroker.bcs.platform.dav.bizapi.constants.status.ExtendGroupDefaultStatus;
import com.cloudbroker.bcs.platform.dav.bizapi.constants.status.ExtendGroupStatus;
import com.cloudbroker.bcs.platform.dav.bizapi.constants.status.NeedLoginStatus;
import com.cloudbroker.bcs.platform.dav.bizapi.constants.type.PlugsContentSource;
import com.cloudbroker.bcs.platform.dav.bizapi.constants.type.TermType;
import com.cloudbroker.bcs.platform.dav.bizapi.service.business.plugs.ExtendGroupBizService;
import com.cloudbroker.bcs.platform.dav.bizapi.service.business.plugs.result.ExtendAppOrderResult;
import com.cloudbroker.bcs.platform.dav.bizapi.service.business.plugs.result.ExtendAppWithPlugsResult;
import com.cloudbroker.bcs.platform.dav.bizapi.service.business.plugs.result.ExtendGroupListResult;
import com.cloudbroker.bcs.platform.dav.bizapi.service.business.plugs.result.ExtendGroupResult;
import com.cloudbroker.bcs.platform.dav.bizapi.service.business.plugs.result.ListWithExtendAppListData;
import com.cloudbroker.bcs.platform.dav.bizapi.service.business.plugs.result.PlugsDavListData;
import com.cloudbroker.bcs.platform.dav.bizapi.service.business.plugs.vo.ExtendAppOrderForm;
import com.cloudbroker.bcs.platform.dav.bizapi.service.business.plugs.vo.ExtendGroupBlankForm;
import com.cloudbroker.bcs.platform.dav.bizapi.service.business.plugs.vo.ExtendGroupBuildDefaultForm;
import com.cloudbroker.bcs.platform.dav.bizapi.service.business.plugs.vo.ExtendGroupListForm;
import com.cloudbroker.bcs.platform.dav.bizapi.service.business.plugs.vo.ExtendGroupSaveForm;
import com.cloudbroker.bcs.platform.dav.bizapi.service.business.plugs.vo.ExtendGroupUpdateForm;
import com.cloudbroker.bcs.platform.dav.common.util.SessionHelper;
import com.cloudbroker.bcs.platform.dav.middle.context.HSBCPSBizDataContext;
import com.cloudbroker.bcs.platform.dav.middle.entity.Broker;
import com.cloudbroker.bcs.platform.dav.middle.entity.ExtendApp;
import com.cloudbroker.bcs.platform.dav.middle.entity.ExtendAppGroup;
import com.cloudbroker.bcs.platform.dav.middle.entity.ExtendGroup;
import com.cloudbroker.bcs.platform.dav.middle.entity.Plugs;
import com.cloudbroker.bcs.platform.dav.middle.entity.WechatShare;
import com.cloudbroker.bcs.platform.dav.middle.service.BrokerService;
import com.cloudbroker.bcs.platform.dav.middle.service.ExtendAppGroupService;
import com.cloudbroker.bcs.platform.dav.middle.service.ExtendAppService;
import com.cloudbroker.bcs.platform.dav.middle.service.ExtendGroupService;
import com.cloudbroker.bcs.platform.dav.middle.service.PlugsService;
import com.cloudbroker.bcs.platform.dav.middle.service.WechatShareService;
import com.hundsun.jres.common.util.UUID;

@Service
public class ExtendGroupBizServiceImpl implements ExtendGroupBizService{
	
	private Logger logger = Logger.getLogger(this.getClass());
	
	@Resource
	private ExtendGroupService extendGroupService;
	
	@Resource
	private ExtendAppService extendAppService;
	
	@Resource
	private ExtendAppGroupService extendAppGroupService;
	
	@Resource
	private BrokerService brokerService;
	
	@Resource
	private PlugsService plugsService;
	
	@Resource
	private WechatShareService weChatShareService;
	
	
	public ExtendGroupListResult funcExtendGroupList(ExtendGroupBlankForm form){
		ExtendGroupListResult result = new ExtendGroupListResult();
		
		Long broker_id = HSBCPSBizDataContext.getBrokerId();
		
		ExtendGroup group = new ExtendGroup();
		group.setBroker_id(broker_id);
		group.setTenant_id(HSBCPSBizDataContext.getTenantId());
		group.setExtend_group_status(ExtendGroupStatus.USING.getVal());
		
		int count = extendGroupService.count(group);
		if(MathUtils.isZero(count)){
			this.initExtendGroup(broker_id,HSBCPSBizDataContext.getTenantId());
		}
		
		List<ListWithExtendAppListData> list = extendGroupService.listGroupWithExtendApp(HSBCPSBizDataContext.getBrokerId(), HSBCPSBizDataContext.getTenantId());
		
		result.newDataList().addAll(list);
		return VOUtil.setSuccessResult(result);
	}
	
	
	public HSBCPSBackVO funcExtendGroupSave(ExtendGroupSaveForm form){
		ExtendGroupResult result = new ExtendGroupResult();
		ExtendGroup g = new ExtendGroup();
		g.setBroker_id(HSBCPSBizDataContext.getBrokerId());
		g.setTenant_id(HSBCPSBizDataContext.getTenantId());
		g.setExtend_group_status(ExtendGroupStatus.USING.getVal());
		
		Integer count = extendGroupService.count(g);
		if(count > 4){
		    return VOUtil.genErrorResult(ExtendGroupErr.EXTEND_GROUP_MAX, HSBCPSBackVO.class);
		}
		
		g.setExtend_group_key(UUID.randomUUID().toString());
		g.setName(form.getName());
		g.setCreate_time(new Date());
		g.setSort(0L);
		g.setLink(getWeChatShareLink(g.getBroker_id(), g.getTenant_id(), g.getExtend_group_key(), ""));
		g.setIs_default(ExtendGroupDefaultStatus.NOT_DEFAULT.getVal());
		extendGroupService.save(g);
		
		return VOUtil.setSuccessResult(result);
	}
	
	public HSBCPSBackVO funcExtendGroupUpdate(ExtendGroupUpdateForm form){
		ExtendGroupResult result = new ExtendGroupResult();
		
		if(StringUtil.isBlank(form.getExtend_group_id())){
			return VOUtil.genErrorResult(ExtendGroupErr.EXTEND_GROUP_ID_IS_NULL, ExtendGroupResult.class);
		}
		
		ExtendGroup g = extendGroupService.get(form.getExtend_group_id());
		if(g == null){
			return VOUtil.genErrorResult(ExtendGroupErr.EXTEND_GROUP_NOT_FUND, ExtendGroupResult.class);
		}
		
        String link = getWeChatShareLink(HSBCPSBizDataContext.getBrokerId(), HSBCPSBizDataContext.getTenantId(), g.getExtend_group_key(), form.getLink());
        if(StringUtil.isEmpty(link)){
            return VOUtil.genErrorResult(WechatShareErr.WECHAT_SHARE_LINK_NOT_SETTING, ExtendAppOrderResult.class);
        }
		
        if(!StringUtil.isEmpty(form.getName())){
            g.setName(form.getName());
        }
        if(!StringUtil.isEmpty(form.getLink())){
            g.setLink(link);
        }
        if(!StringUtil.isEmpty(form.getQrcode_url())){
            g.setQrcode_url(form.getQrcode_url());
        }
		extendGroupService.update(g);
		return VOUtil.setSuccessResult(result);
	}
	
	public ExtendGroupResult funcExtendGroupDel(ExtendGroupListForm form){
		ExtendGroupResult result = new ExtendGroupResult();
		
		ExtendGroup extendGroup = extendGroupService.get(form.getExtend_group_id());
		if(extendGroup == null){
		    return VOUtil.genErrorResult(ExtendGroupErr.EXTEND_GROUP_NOT_FUND, ExtendGroupResult.class);
		}
		
		if(extendGroup.getIs_default() == ExtendGroupDefaultStatus.IS_DEFAULT.getVal()){
		    return VOUtil.genErrorResult(ExtendGroupErr.EXTEND_GROUP_DEFAULT_UNDEL, ExtendGroupResult.class);
		}
		
		extendAppGroupService.delByCondition(null,form.getExtend_group_id(),null, HSBCPSBizDataContext.getTenantId());
        extendGroupService.delete(form.getExtend_group_id());
		
		return VOUtil.setSuccessResult(result);
	}
	
	
	public ExtendGroup initExtendGroup(Long broker_id,Integer tenant_id){
		ExtendGroup g = new ExtendGroup();
		g.setBroker_id(broker_id);
		g.setSort(extendGroupService.getMaxSort(g));
		g.setExtend_group_key(UUID.randomUUID().toString());
		g.setName(ExtendGroupDefaultStatus.IS_DEFAULT.getDescription());
		g.setDescription("");
		g.setCreate_time(new Date());
		g.setExtend_group_status(ExtendGroupStatus.USING.getVal());
		g.setIs_default(ExtendGroupDefaultStatus.IS_DEFAULT.getVal());
		g.setLink(getWeChatShareLink(broker_id, tenant_id, g.getExtend_group_key(),""));
		g.setTenant_id(tenant_id);
		extendGroupService.save(g);
		logger.info("添加分组的主键值" + g.getExtend_group_id());
		return g;
	}


	@Override
	public HSBCPSBackVO funcExtendGroupBuildDefault(
			ExtendGroupBuildDefaultForm form) {
		try {
			Broker broker = brokerService.get(form.getBroker_id());
			if(broker == null){
			    return VOUtil.genErrorResult(ClientErr.BROKER_NOT_FIND,HSBCPSBackVO.class);
			}
			
			Plugs selectPara = new Plugs();
			Pagination page = new Pagination();
			
			selectPara.setTerm_type(String.valueOf(TermType.FANS.getVal()));
	        page.setPage_no(1);
	        page.setPage_size(10);
	        
	        selectPara.setPage(page);
	        
	        List<PlugsDavListData> list = plugsService.queryPlugsForWeb(selectPara, page);
            if(list == null || list.isEmpty()){
                return VOUtil.genErrorResult(PlugsErr.PLUGS_NOT_EXIST, HSBCPSBackVO.class);
            }
            
            extendAppService.deleteByCondition(form.getBroker_id(), broker.getTenant_id());
            for (PlugsDavListData p : list) {
                ExtendApp app = new ExtendApp();
                app.setBroker_id(Long.valueOf(form.getBroker_id()));
                app.setSort(extendAppService.getMaxSort(app));
                app.setName(p.getName());
                app.setCreater(p.getCreater());
                app.setPlugs_id(Long.valueOf(p.getPlugs_id()));
                app.setExtend_app_status(1);
                app.setLink(p.getLink());
                app.setCharge_mod(Integer.valueOf(p.getCharge_mod()));
                app.setUsed(0);
                app.setStart_time(new Date());
                app.setValid_time(DateUtil.strToDate("2099-01-01", DateUtil.YYYY_MM_DD));
                app.setCount(100000);
                app.setTenant_id(broker.getTenant_id());
                app.setTerm_type(p.getTerm_type());
                app.setPrice(p.getDiscount_price());
                app.setMust_login(Integer.valueOf(p.getMust_login()));
                extendAppService.save(app);
            }
            
            //处理分组
            extendAppGroupService.delByCondition(form.getBroker_id(),null,null, broker.getTenant_id());
            extendGroupService.deleteByCondition(form.getBroker_id(), broker.getTenant_id());
            ExtendGroup group = initExtendGroup(Long.valueOf(form.getBroker_id()),broker.getTenant_id());
            
            //处理分组与应用关系
            ExtendApp app = new ExtendApp();
            app.setBroker_id(Long.valueOf(form.getBroker_id()));
            app.setTenant_id(broker.getTenant_id());
            List<ExtendApp> apps = extendAppService.query(app);
            if(apps != null && apps.size() > 0){
                ExtendApp extendApp = null;
                for(int i =0;i<apps.size();i++){
                    if(i >= 5){break;}
                    extendApp = apps.get(i);
                    ExtendAppGroup appGroup = new ExtendAppGroup();
                    appGroup.setExtend_group_id(group.getExtend_group_id());
                    appGroup.setSort(extendAppGroupService.getMaxSort(appGroup));
                    appGroup.setExtend_app_id(extendApp.getExtend_app_id());
                    appGroup.setNeed_login("观点".equals(extendApp.getName()) || "问答".equals(extendApp.getName()) ? 0 : 1);
                    appGroup.setPersonal_attr("[]");
                    appGroup.setTenant_id(broker.getTenant_id());
                    extendAppGroupService.save(appGroup);
                }
            } else {
                return VOUtil.genErrorResult(ExtendGroupErr.EXTEND_GROUP_DEFAULT_BUILD_FAIL, HSBCPSBackVO.class);
            }
		} catch (Exception e) {
			logger.error("生成默认分组出错", e);
			return VOUtil.genErrorResult(ExtendGroupErr.EXTEND_GROUP_DEFAULT_BUILD_FAIL, HSBCPSBackVO.class);
		}
		SessionHelper.getInstance().clearNewNeedLoginExtendAppsByBrokerId(HSBCPSBizDataContext.getBrokerId(), "");
		return VOUtil.genSuccessBackVo();
	}
	
	public ExtendAppOrderResult funcExtendAppBuildGroup(ExtendAppOrderForm form) {
		ExtendAppOrderResult result = new ExtendAppOrderResult();
		try {
			JSONArray extendAppList = JSONArray.fromObject(form.getExtend_app_list());
			Long extend_group_id = Long.valueOf(form.getExtend_group_id());
			
			if(extendAppList == null || extendAppList.isEmpty()){
			    return VOUtil.genErrorResult(ExtendGroupErr.EXTEND_GROUP_JSONARRAY_NOT_NULL, ExtendAppOrderResult.class);
			}
			
            ExtendGroup group = new ExtendGroup();
            group.setExtend_group_id(extend_group_id);
            group.setBroker_id(HSBCPSBizDataContext.getBrokerId());
            group.setTenant_id(HSBCPSBizDataContext.getTenantId());
            Integer groupCount = extendGroupService.count(group);
            if(MathUtils.isZero(groupCount)){
                return VOUtil.genErrorResult(ExtendGroupErr.EXTEND_APP_BUILD_GROUP_NOT_EXIST, ExtendAppOrderResult.class);
            }
			
            List<ExtendAppGroup> saveList = new ArrayList<ExtendAppGroup>();
            List<Long> idList = new ArrayList<Long>();
            for (Object jo : extendAppList) {
                JSONObject extendAppJson = JSONObject.fromObject(jo);
                Long extend_app_id = Long.valueOf(extendAppJson.get("extend_app_id").toString());
                
                //重复数据检测
                if(idList.contains(extend_app_id)){
                    continue;
                }
                idList.add(extend_app_id);
                
                ExtendApp app = new ExtendApp();
                app.setExtend_app_id(extend_app_id);
                app.setBroker_id(HSBCPSBizDataContext.getBrokerId());
                app.setTerm_type(String.valueOf(TermType.FANS.getVal()));
                app.setTenant_id(HSBCPSBizDataContext.getTenantId());
                Integer extendAppCount = extendAppService.count(app);
                if(MathUtils.isZero(extendAppCount)){
                    return VOUtil.genErrorResult(ExtendGroupErr.EXTEND_APP_BUILD_APP_NOT_EXIST, ExtendAppOrderResult.class);
                }
                
                ExtendAppGroup g = new ExtendAppGroup();
                g.setExtend_app_id(extend_app_id);
                g.setExtend_group_id(extend_group_id);
                g.setTenant_id(HSBCPSBizDataContext.getTenantId());
                Integer existCount = extendAppGroupService.count(g);
                if(existCount > 0){
                    continue;
                }

                g.setNeed_login(Integer.valueOf(extendAppJson.optInt("need_login",NeedLoginStatus.LOGIN.getVal())));
                g.setPersonal_attr(extendAppJson.optString("personal_attr","[]"));
                g.setSort(extendAppJson.optLong("sort",0));
                saveList.add(g);
            }
            //分组中应用数 不能超过7个检测
            /*            ExtendAppGroup groupAppCount = new ExtendAppGroup();
            groupAppCount.setExtend_group_id(extend_group_id);
            Integer count = extendAppGroupService.count(groupAppCount);
            if((saveList.size() + count) > 5) {
                return VOUtil.genErrorResult(ExtendGroupErr.EXTEND_APP_GROUP_MAX, ExtendAppOrderResult.class);
            }*/
            
            /**
             * 首次添加组件时需要检测 第一个是否是外链组件
             */
            ExtendAppGroup extendAppGroup = new ExtendAppGroup();
            extendAppGroup.setTenant_id(HSBCPSBizDataContext.getTenantId());
            extendAppGroup.setExtend_group_id(extend_group_id);
            int groupAppCount = extendAppGroupService.count(extendAppGroup);
            if(MathUtils.isZero(groupAppCount)){
            	saveList = reSortList(saveList);
                if(saveList == null){
                    return VOUtil.genErrorResult(ExtendGroupErr.EXTEND_APP_GROUP_FULL_OUTSIDE_PLUGS, ExtendAppOrderResult.class);
                }
            }
            
            for (ExtendAppGroup saveDb : saveList) {
                if(MathUtils.isZero(saveDb.getSort())){
                    ExtendAppGroup maxSortBean = new ExtendAppGroup();
                    maxSortBean.setExtend_group_id(extend_group_id);
                    maxSortBean.setTenant_id(HSBCPSBizDataContext.getTenantId());
                    saveDb.setSort(extendAppGroupService.getMaxSort(maxSortBean));
               }
                extendAppGroupService.save(saveDb);
            }
			
		} catch (Exception e) {
			logger.error("funcExtendAppBuildGroup failed "+e.getMessage());
			return VOUtil.genErrorResult(ExtendGroupErr.EXTEND_APP_BUILD_GROUP_FAIL, ExtendAppOrderResult.class);
		}
		
		SessionHelper.getInstance().clearNewNeedLoginExtendAppsByBrokerId(HSBCPSBizDataContext.getBrokerId(), "");
		return VOUtil.setSuccessResult(result);
	}
	
	/**
	 * 执行重排序，保证分组中第一个组件一定不是 外链
	 * @param list
	 * @return
	 */
	public List<ExtendAppGroup> reSortList(List<ExtendAppGroup> list){
	    List<ExtendAppGroup> newList = new ArrayList<ExtendAppGroup>();
	    for(Iterator<ExtendAppGroup> iterator = list.iterator();iterator.hasNext();){
	        ExtendAppGroup extendAppGroup = iterator.next();
	        
            ExtendAppWithPlugsResult appProp = extendAppService.getAppPropById(extendAppGroup);
            if(PlugsContentSource.MIDDLE.getVal().equals(appProp.getContent_source())){
                newList.add(extendAppGroup);
                iterator.remove();
                break;
            }
	    }
	    if(newList.size() == 0){
	        return null;
	    }
	    newList.addAll(list);
	    return newList;
	}
	
	public String getWeChatShareLink(Long broker_id,Integer tenant_id,String extend_group_key,String link){
		
		if(StringUtil.isEmpty(link)) {
			WechatShare wShare = new WechatShare();
			wShare.setBroker_id(broker_id);
			wShare.setTenant_id(tenant_id);
			List<WechatShare> shareList = weChatShareService.query(wShare);
			if(shareList != null && shareList.size() > 0){
				link = shareList.get(0).getLink_url();
			}
		}
		
		link = link.endsWith(";") ? link : link + ";";
		link = link + "gkey:" + extend_group_key;
		return link;
	}
}
